<template>
  <pageContainer class="contentRole">
    <template slot="header">
      <div class="title">
        <i class="line"></i>
        <p class="text">查询条件</p>
      </div>
      <div class="search">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="权限字符" prop="roleKey">
        <el-input
          v-model="queryParams.roleKey"
          placeholder="请输入权限字符"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="角色状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="getTable">查询</el-button>
            <el-button size="small" type="primary" @click="add" v-hasPermi="['system:role:add']">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template slot="center">
      <div class="title">
        <i class="line"></i>
        <p class="text">角色列表</p>
      </div>
      <div class="table" ref="table">
        <el-table

          :data="tableData"
          :header-cell-style="{textAlign: 'center',color: '#fff',backgroundColor: '#223450'}"
          style="width: 100%;height:100%">
          <el-table-column
          align="center"
            type="index"
            width="100"
            label="序号">
          </el-table-column>
          <el-table-column
          align="center"
            prop="roleName"
            label="角色名称">
          </el-table-column>
           <el-table-column label="状态" align="center" width="100" v-hasPermi="['system:role:edit']">
            <template slot-scope="scope">
              <el-switch
                v-if="scope.row.roleId !== 1"
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
         <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
          </el-table-column>
          <el-table-column
          align="center"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.roleId !== 1" @click="handleUpdate(scope.row)" style="padding:0" v-hasPermi="['system:role:edit']">修改</el-button>
              <el-button type="text" v-if="scope.row.roleId !== 1"  @click="handleDelete(scope.row)" style="color:red;padding:0" v-hasPermi="['system:role:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
    <template slot="bottom">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- <DialogVisible v-if="dialog.roleVisible" :dialog="dialog" @handleClose="handleClose"/> -->
       <el-dialog :title="dialog.title" :visible.sync="dialog.roleVisible" width="500px" append-to-body :before-close="cancel">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色权限" prop="roleKey">
            <el-input v-model="form.roleKey" placeholder="请输入角色权限" />
          </el-form-item>
          <el-form-item label="角色排序" prop="roleSort">
            <el-input v-model="form.roleSort" placeholder="请输入角色排序" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="菜单权限" prop="treeList">
            <el-tree
              class="tree-border"
              :data="menuOptions"
              show-checkbox
              ref="menu"
              node-key="id"
              empty-text="加载中，请稍候"
              :props="defaultProps"
            ></el-tree>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </template>

  </pageContainer>
</template>

<script>

import pageContainer from '../../../components/pageContainer.vue'
import { roleList, treeselect, changeRoleStatus, addRole, updateRole, delRole, getRole, roleMenuTreeselect } from '@/api/systemSettings'
import { dict } from '@/utils/dict'
export default {
  components: { pageContainer },
  data() {
    const validTree = (rule, value, callback) => {
      // 获取选中节点数组
      const arr = this.$refs.menu.getCheckedKeys()
      if (!arr || arr.length === 0) {
        callback(new Error('请选择菜单权限'))
      } else {
        callback()
      }
    }
    return {
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined
      },
      dict: dict,
      tableData: [],
      menuOptions: [],
      form: {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        status: '',
        menuIds: [],
        deptIds: [],
        roleSort: null,

        remark: undefined
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '请输入角色权限', trigger: 'blur' }
        ],
        roleSort: [
          { required: true, message: '请输入角色排序', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        // remark:[
        //   { required: true, message: '请输入备注', trigger: 'blur' },
        // ],
        treeList: [
          { required: true, validator: validTree, trigger: 'change' }
        ]
      },
      ids: [],
      maxHeight: null,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dialog: {
        roleVisible: false,
        title: ''
      }
    }
  },
  mounted() {
    this.getMaxTableHeight()
    this.getTable()
    this.treeselect()
  },
  watch: {
    maxHeight: {
      handler(newV) {
        this.maxHeight = newV
      },
      deep: true
    }
  },
  methods: {
    // 取消按钮
    cancel() {
      this.dialog.roleVisible = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      if (this.$refs.menu !== undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      this.form = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        status: '',
        menuIds: [],
        deptIds: [],
        roleSort: null
      }
      if (this.$refs.form !== undefined) {
        this.$refs.form.resetFields()
      }
    },
    // 角色状态修改
    handleStatusChange(row) {
      const text = row.status === '0' ? '启用' : '停用'
      this.$confirm('确认要"' + text + '""' + row.roleName + '"角色吗？').then(function() {
        return changeRoleStatus(row.roleId, row.status)
      }).then(() => {
        this.$message.success('操作成功！')
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    treeselect() {
      treeselect().then(res => {
        // console.log(res)
        this.menuOptions = res.data
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 新增
    add() {
      this.dialog.roleVisible = true
      this.dialog.title = '新增'
    },
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.roleId !== undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            updateRole(this.form).then(response => {
              // this.$modal.msgSuccess('修改成功')
              this.dialog.roleVisible = false
              this.reset()
              this.getTable()
            })
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            addRole(this.form).then(response => {
              // this.$modal.msgSuccess('新增成功')
              this.dialog.roleVisible = false
              this.reset()
              this.getTable()
            })
          }
        }
      })
    },
    handleUpdate(row) {
      this.reset()
      const roleId = row.roleId || this.ids
      const roleMenu = this.getRoleMenuTreeselect(roleId)
      getRole(roleId).then(response => {
        this.form = response.data
        this.dialog.roleVisible = true
        this.$nextTick(() => {
          roleMenu.then(res => {
            const checkedKeys = res.data.checkedKeys
            checkedKeys.forEach((v) => {
              this.$nextTick(() => {
                this.$refs.menu.setChecked(v, true, false)
              })
            })
          })
        })

        this.dialog.title = '修改'
      })
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.data.menus
        return response
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId || this.ids
      this.$confirm('是否确认删除此角色？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delRole(roleIds)
      }).then(() => {
        this.getTable()
      }).catch(() => {})
    },
    handleClose() {
      this.dialog.roleVisible = false
    },
    getMaxTableHeight() {
      const windowInnerHeight = this.$refs.table
      this.maxHeight = windowInnerHeight.offsetHeight
    },
    getTable() {
      roleList(this.queryParams).then(res => {
        // console.log(res)
        this.tableData = res.rows
        this.total = res.total
      })
    },
    handleSizeChange(val) {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = val
      this.getTable()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getTable()
    }

  }
}
</script>

<style lang="scss" scoped>
.contentRole{
  .title{
    display: flex;
    align-items: center;
    height: 30px;
    .line{
      width: 5px;
      height: 25px;
      background: #409EFF;
      margin-right: 5px;
    }
    .text{
      color: #fff;
    }
  }
  .search{
    height: calc(100% - 30px);
    display: flex;
    align-items: center;
    .demo-form-inline{
      padding-left: 10px;
      :deep(.el-form-item){
        margin-bottom: 0;
      }
    }
  }
  .table{
    max-height: calc(100% - 40px);
    margin-top: 10px;
    :deep(.el-table__body-wrapper){
      max-height: 544px;
      overflow-y: auto;
    }
  }
}
/*最外层透明*/
:deep(.el-table), :deep(.el-table__expanded-cell){
  background-color: transparent;
}
/* 表格内背景颜色 */
:deep(.el-table th),
:deep(.el-table tr),
:deep(.el-table td) {
  background-color: transparent;
  color: #C9E9FF;
  height: 30px;
}
:deep(.el-table thead) {
  color: #7EC1FF;
  font-size: 14px;
}
:deep(.el-table--enable-row-hover){
   background-color: transparent;
}
:deep(.el-table .warning-row) {
 background: rgba(51, 91, 127, 0.6);
}
:deep(.el-table){
  --el-table-border-color: rgba(51, 91, 127, 0.6) !important;

}
:deep(.el-table tbody tr:hover > td) {
            background: rgba(51, 91, 127, 0.4) !important;
        }
   :deep(.el-input__inner){
  background: rgba(51, 91, 127, 1);
  box-shadow:none;
  border:none;
  color: #fff;

}
:deep(.el-pager li){
  background: rgba(51, 91, 127, 1);
  box-shadow:none;
  border:none;
  color: #fff;
}
:deep(.btn-prev){
  background: rgba(51, 91, 127, 1);
  box-shadow:none;
  border:none;
  color: #fff;
}
:deep(.el-pagination button:disabled){
  background: rgba(51, 91, 127, 1);
  box-shadow:none;
  border:none;
  color: #fff;

}
:deep(.el-pagination__total),:deep(.el-pagination__jump){
  color: #fff;
}
:deep(.el-table td.el-table__cell),:deep(.el-table th.el-table__cell.is-leaf){
  border-color: rgba(231,234,241,0.2);
}
:deep(.el-table::before){
  background: rgba(231,234,241,0.2);
}
:deep(.el-form-item__label){
  color: #A3B3BE;
}
:deep(.el-dialog){
  background: rgba(0,28,55,0.85);
}
:deep(.el-dialog__header){
  border-bottom: 1px solid rgba(120, 189, 255, 1);
  margin-right: 0px;
  margin-bottom:10px
}
:deep(.el-dialog__title){
  color: #41B0FF;
  font-size: 16px;
}

:deep(.el-dialog__headerbtn .el-dialog__close){
  color: rgba(70, 174, 255, 1);
}
:deep(.el-tree){
  background: rgba(3, 27, 54, 0.7);
}
:deep(.el-tree-node__content:hover) {
    background-color: #65a19f !important;
}
:deep(.el-tree-node:focus>.el-tree-node__content){
    background: #65a19f !important;
}
:deep(.el-textarea__inner){
  background: rgb(51, 91, 127);
  box-shadow:none;
  border:none;
  color: #fff;
}
</style>
